package Vista;

import Controlador.ControlCliente;
import Controlador.ControlFactura;
import Controlador.ControlFacturaDetalles;
import Controlador.ControlPedido;
import Controlador.ControlPedidoDetalles;
import Controlador.ControlProducto;
import Controlador.ControlVendedor;
import Modelo.Cliente;
import Modelo.PanelConFondo;
import Modelo.Pedido;
import Modelo.Reporte;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

public class FacturaRegistrar extends javax.swing.JFrame implements TableModelListener{
  ControlPedido pedido=new ControlPedido();
  ControlFactura factura=new ControlFactura();
  ControlCliente cliente=new ControlCliente();
  ControlVendedor vendedor=new ControlVendedor();
  ControlProducto producto=new ControlProducto();
  ControlPedidoDetalles pedidoDetalles=new ControlPedidoDetalles();
  ControlFacturaDetalles facturaDetalles=new ControlFacturaDetalles();
  ProductoConsultar menuConsultaProducto;

  //Calendar fecha =  Calendar.getInstance();
 // Calendar fechaActual = new GregorianCalendar();
  java.sql.Date fechaActual;

  DefaultTableModel tablaModelo;
  //private double valorFacturado=0;

    //Constructor
     public FacturaRegistrar() throws SQLException {
        initComponents();
        ((PanelConFondo) panelFondo).setImagen("/rutascoronasa/resources/Imagenes/generacion de facturas.png");
        //modPedido.connect();

        //fecha actual del sistema
        java.util.Date utilDate = new java.util.Date();
        fechaActual= new java.sql.Date(utilDate.getTime());
        jLabelFecha.setText(fechaActual.toString());

        //centra el frame en la pantalla
        this.setLocationRelativeTo(null);
        jTextNoPedido.setText("");
        jLabelConsFactura.setText((factura.getConsecutivo()+1)+"");

        ajustaTabla();
        tablaModelo=(DefaultTableModel) jTableConsulta.getModel();
        tablaModelo.addTableModelListener((TableModelListener) this);
       
        
        pedidoDetalles.cleanTabla(jTableConsulta);//limpio la tabla
        tablaModelo.addRow(new Object[]{""});
     
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel5 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jButtonPedido = new javax.swing.JButton();
        jButtonFacturar = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableConsulta = new javax.swing.JTable();
        jButtonEliminar = new javax.swing.JButton();
        jButtonNueva = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jTextDireccion = new javax.swing.JTextField();
        jTextEstablecimiento = new javax.swing.JTextField();
        jTextNombre = new javax.swing.JTextField();
        jTextCedula = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jTextCodigoVendedor = new javax.swing.JTextField();
        jTextTelefono = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jTextCodigo = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabelFecha1 = new javax.swing.JLabel();
        jLabelConsFactura = new javax.swing.JLabel();
        jLabelFecha3 = new javax.swing.JLabel();
        jTextNoPedido = new javax.swing.JTextField();
        jLabelFecha = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabelSubTotal = new javax.swing.JLabel();
        jLabelIva = new javax.swing.JLabel();
        jLabelTotal = new javax.swing.JLabel();
        panelFondo = new Modelo.PanelConFondo();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextObservaciones = new javax.swing.JTextArea();
        jLabel15 = new javax.swing.JLabel();
        jButtonSalir = new javax.swing.JButton();

        jPanel5.setBackground(new java.awt.Color(255, 255, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));
        jPanel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(0, 51, 0), new java.awt.Color(0, 51, 0), null, null));

        jButtonPedido.setFont(new java.awt.Font("Tahoma", 0, 16));
        jButtonPedido.setForeground(new java.awt.Color(51, 0, 0));
        jButtonPedido.setText("Generar Pedido");
        jButtonPedido.setEnabled(false);
        jButtonPedido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPedidoActionPerformed(evt);
            }
        });
        jButtonPedido.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButtonPedidoKeyPressed(evt);
            }
        });

        jButtonFacturar.setFont(new java.awt.Font("Tahoma", 0, 16));
        jButtonFacturar.setForeground(new java.awt.Color(51, 0, 0));
        jButtonFacturar.setText("Generar Facturar");
        jButtonFacturar.setEnabled(false);
        jButtonFacturar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFacturarActionPerformed(evt);
            }
        });
        jButtonFacturar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButtonFacturarKeyPressed(evt);
            }
        });

        jPanel6.setBackground(new java.awt.Color(255, 255, 255));
        jPanel6.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(0, 51, 0), new java.awt.Color(0, 51, 0), new java.awt.Color(51, 102, 0), new java.awt.Color(0, 51, 0)));
        jPanel6.setForeground(new java.awt.Color(0, 0, 154));

        jLabel10.setBackground(new java.awt.Color(255, 255, 255));
        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel10.setForeground(new java.awt.Color(153, 0, 0));
        jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel10.setText("Detalles de Factura");

        jTableConsulta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Item No.", "Codigo", "Descripcion", "Existencia", "Cant. Solitada", "Cant. Facturada", "Valor Un.", "Valor Bruto", "%IVA", "Valor Neto"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, false, false, true, true, true, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableConsulta.setEnabled(false);
        jTableConsulta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTableConsultaKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTableConsulta);

        jButtonEliminar.setFont(new java.awt.Font("Tahoma", 0, 16));
        jButtonEliminar.setForeground(new java.awt.Color(51, 0, 0));
        jButtonEliminar.setText("Eliminar Producto");
        jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarActionPerformed(evt);
            }
        });
        jButtonEliminar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButtonEliminarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 970, Short.MAX_VALUE)
                    .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 970, Short.MAX_VALUE)
                    .addComponent(jButtonEliminar, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jButtonNueva.setFont(new java.awt.Font("Tahoma", 0, 16));
        jButtonNueva.setForeground(new java.awt.Color(51, 0, 0));
        jButtonNueva.setText("Cancelar");
        jButtonNueva.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNuevaActionPerformed(evt);
            }
        });
        jButtonNueva.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButtonNuevaKeyPressed(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(0, 51, 0), new java.awt.Color(0, 51, 0), new java.awt.Color(51, 102, 0), new java.awt.Color(0, 51, 0)));
        jPanel3.setForeground(new java.awt.Color(0, 0, 154));

        jLabel2.setBackground(new java.awt.Color(255, 255, 255));
        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel2.setForeground(new java.awt.Color(153, 0, 0));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Datos del Cliente");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel4.setForeground(new java.awt.Color(51, 0, 0));
        jLabel4.setText("Codigo:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel5.setForeground(new java.awt.Color(51, 0, 0));
        jLabel5.setText("Apellidos/Nombre:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel6.setForeground(new java.awt.Color(51, 0, 0));
        jLabel6.setText("Establecimiento:");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel7.setForeground(new java.awt.Color(51, 0, 0));
        jLabel7.setText("Direccion:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel8.setForeground(new java.awt.Color(51, 0, 0));
        jLabel8.setText("Telefono:");

        jTextDireccion.setEditable(false);

        jTextEstablecimiento.setEditable(false);

        jTextNombre.setEditable(false);

        jTextCedula.setEditable(false);

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel9.setForeground(new java.awt.Color(51, 0, 0));
        jLabel9.setText("Vendedor:");

        jTextCodigoVendedor.setEditable(false);
        jTextCodigoVendedor.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextCodigoVendedorFocusGained(evt);
            }
        });
        jTextCodigoVendedor.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextCodigoVendedorKeyPressed(evt);
            }
        });

        jTextTelefono.setEditable(false);

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel12.setForeground(new java.awt.Color(51, 0, 0));
        jLabel12.setText("Cedula/Nit:");

        jTextCodigo.setEditable(false);
        jTextCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextCodigoFocusGained(evt);
            }
        });
        jTextCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextCodigoKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 970, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextEstablecimiento, javax.swing.GroupLayout.DEFAULT_SIZE, 696, Short.MAX_VALUE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, 673, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel8)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextCodigoVendedor, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jTextTelefono)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextCodigo, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(jTextCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12)
                    .addComponent(jTextCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(jLabel6)
                    .addComponent(jTextEstablecimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(jTextCodigoVendedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jTextDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)
                    .addComponent(jTextTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(0, 51, 0), new java.awt.Color(0, 51, 0), new java.awt.Color(0, 51, 0), new java.awt.Color(0, 51, 0)));
        jPanel1.setForeground(new java.awt.Color(0, 0, 154));

        jLabelFecha1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabelFecha1.setForeground(new java.awt.Color(51, 0, 0));
        jLabelFecha1.setText("No. Factura:");

        jLabelConsFactura.setBackground(new java.awt.Color(255, 255, 255));
        jLabelConsFactura.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabelConsFactura.setForeground(new java.awt.Color(102, 0, 0));
        jLabelConsFactura.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelConsFactura.setText("0000001");

        jLabelFecha3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabelFecha3.setForeground(new java.awt.Color(51, 0, 0));
        jLabelFecha3.setText("No. Pedido:");

        jTextNoPedido.setFont(new java.awt.Font("Tahoma", 1, 14));
        jTextNoPedido.setForeground(new java.awt.Color(102, 0, 0));
        jTextNoPedido.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextNoPedido.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextNoPedidoKeyPressed(evt);
            }
        });

        jLabelFecha.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabelFecha.setForeground(new java.awt.Color(153, 0, 0));
        jLabelFecha.setText("12/05/2010");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelFecha1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelConsFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelFecha3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextNoPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 458, Short.MAX_VALUE)
                .addComponent(jLabelFecha)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelFecha1)
                    .addComponent(jLabelConsFactura)
                    .addComponent(jLabelFecha3)
                    .addComponent(jTextNoPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelFecha))
                .addContainerGap())
        );

        jPanel7.setBackground(new java.awt.Color(255, 255, 255));
        jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel11.setForeground(new java.awt.Color(51, 0, 0));
        jLabel11.setText("SubTotal:");

        jLabel13.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel13.setForeground(new java.awt.Color(51, 0, 0));
        jLabel13.setText("Iva:");

        jLabel14.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel14.setForeground(new java.awt.Color(51, 0, 0));
        jLabel14.setText("Total:");

        jLabelSubTotal.setBackground(new java.awt.Color(255, 255, 255));
        jLabelSubTotal.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabelSubTotal.setForeground(new java.awt.Color(153, 0, 0));
        jLabelSubTotal.setText("0.0");

        jLabelIva.setBackground(new java.awt.Color(255, 255, 255));
        jLabelIva.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabelIva.setForeground(new java.awt.Color(153, 0, 0));
        jLabelIva.setText("0.0");

        jLabelTotal.setBackground(new java.awt.Color(255, 255, 255));
        jLabelTotal.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabelTotal.setForeground(new java.awt.Color(153, 0, 0));
        jLabelTotal.setText("0.0");

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelSubTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelIva, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel14)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(107, Short.MAX_VALUE))
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(jLabel11)
                    .addComponent(jLabel14)
                    .addComponent(jLabelSubTotal)
                    .addComponent(jLabelIva)
                    .addComponent(jLabelTotal))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelFondo.setBackground(new java.awt.Color(255, 0, 102));
        panelFondo.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        panelFondo.setOpaque(false);

        javax.swing.GroupLayout panelFondoLayout = new javax.swing.GroupLayout(panelFondo);
        panelFondo.setLayout(panelFondoLayout);
        panelFondoLayout.setHorizontalGroup(
            panelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 992, Short.MAX_VALUE)
        );
        panelFondoLayout.setVerticalGroup(
            panelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 62, Short.MAX_VALUE)
        );

        jPanel8.setBackground(new java.awt.Color(255, 255, 255));
        jPanel8.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 51, 0)));

        jTextObservaciones.setColumns(20);
        jTextObservaciones.setRows(5);
        jScrollPane2.setViewportView(jTextObservaciones);

        jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel15.setForeground(new java.awt.Color(51, 0, 0));
        jLabel15.setText("Observaciones:");

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 972, Short.MAX_VALUE)
                    .addComponent(jLabel15))
                .addContainerGap())
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addComponent(jLabel15)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(panelFondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel4Layout.createSequentialGroup()
                            .addComponent(jButtonFacturar)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButtonPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButtonNueva, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonNueva, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonFacturar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jButtonSalir.setForeground(new java.awt.Color(51, 0, 0));
        jButtonSalir.setText("Finalizar");
        jButtonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonSalir)
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalirActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_jButtonSalirActionPerformed

    private void jTextNoPedidoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextNoPedidoKeyPressed
      if(evt.getKeyCode()==10){           
            if(jTextNoPedido.getText().equalsIgnoreCase("")){
               int siNo=JOptionPane.showConfirmDialog(null,"Desea Que El No. del Pedido Sea Generado");//no =1 si =0
                 if(siNo==0){// RESPONDE SI
                    try {
                        jTextNoPedido.setText((pedido.getConsecutivo()+1)+"");
                    } catch (SQLException ex) {
                        Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    jTextNoPedido.setEditable(false);
                    jTextCodigo.setEditable(true);
                    jTextCodigo.requestFocus();
                 }
            }else{
                try {
                    if (pedido.isExist(jTextNoPedido.getText())) {                        
                            Pedido ped = new Pedido();
                            ped = pedido.getPedido(jTextNoPedido.getText());
                            if(ped.isEstado()==false){
                                if(JOptionPane.showConfirmDialog(null,"El Pedido Ya Se Ha Facturado, Desea Continuar? ")==0){//0=si 1=no                                    
                                   getPedido(ped);
                                }
                            }else{                                    
                                  getPedido(ped);
                            }

                    } else {
                        JOptionPane.showMessageDialog(null, "Pedido no Se Encuentra Registrado...");
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_jTextNoPedidoKeyPressed

    private void jTextCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextCodigoKeyPressed
         if(evt.getKeyCode()==10){
            try {
                verificaConsultaCliente();
            } catch (SQLException ex) {
                Logger.getLogger(ClienteModificar.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jTextCodigoKeyPressed

    private void jTextCodigoVendedorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextCodigoVendedorKeyPressed
        if(evt.getKeyCode()==10){
            try {
                verificaConsultaVendedor();
            } catch (SQLException ex) {
                Logger.getLogger(ClienteModificar.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jTextCodigoVendedorKeyPressed

    private void jTableConsultaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableConsultaKeyPressed
        if(evt.getKeyCode()==10){//********************************************//
            int row=jTableConsulta.getSelectedRow();
            int col=jTableConsulta.getSelectedColumn();
            if(row!=-1)
               //llamarConsultaProducto(row);
              jTableConsulta.editCellAt(row,col);
        }
    }//GEN-LAST:event_jTableConsultaKeyPressed

    private void jTextCodigoVendedorFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextCodigoVendedorFocusGained
        try {
            if (vendedor.isExist(jTextCodigoVendedor.getText())) {
                jTableConsulta.setEnabled(true);
                jTableConsulta.requestFocus();
                jTableConsulta.changeSelection(0, 0, false, false);
                jTextCodigoVendedor.setEditable(false);
            }
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jTextCodigoVendedorFocusGained

    private void jButtonPedidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPedidoActionPerformed
        try {
            registraPedido();
             clean();
            JOptionPane.showMessageDialog(null,"Operacion Exitosa...!");
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonPedidoActionPerformed

    private void jButtonPedidoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButtonPedidoKeyPressed
        if(evt.getKeyCode()==10)
            try {
            registraPedido();
             clean();
            JOptionPane.showMessageDialog(null,"Operacion Exitosa...!");
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonPedidoKeyPressed

    private void jButtonNuevaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNuevaActionPerformed
        clean();
    }//GEN-LAST:event_jButtonNuevaActionPerformed

    private void jButtonNuevaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButtonNuevaKeyPressed
       if(evt.getKeyCode()==10)
         clean();
    }//GEN-LAST:event_jButtonNuevaKeyPressed

    private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
        try {
            eliminarProducto();
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonEliminarActionPerformed

    private void jButtonEliminarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButtonEliminarKeyPressed
        if(evt.getKeyCode()==10)
           try {
            eliminarProducto();
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonEliminarKeyPressed

    private void jButtonFacturarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFacturarActionPerformed
        try {
            registraFactura();            
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonFacturarActionPerformed

    private void jButtonFacturarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButtonFacturarKeyPressed
        if(evt.getKeyCode()==10)
            try {
            registraFactura();                     
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonFacturarKeyPressed

    private void jTextCodigoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextCodigoFocusGained
        try {
            if (cliente.isExistCodigo(jTextCodigo.getText())) {
                verificaConsultaCliente();
                jTextCodigo.setEditable(false);
            }
        } catch (SQLException ex) {
            Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jTextCodigoFocusGained


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JButton jButtonFacturar;
    private javax.swing.JButton jButtonNueva;
    private javax.swing.JButton jButtonPedido;
    private javax.swing.JButton jButtonSalir;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelConsFactura;
    private javax.swing.JLabel jLabelFecha;
    private javax.swing.JLabel jLabelFecha1;
    private javax.swing.JLabel jLabelFecha3;
    private javax.swing.JLabel jLabelIva;
    private javax.swing.JLabel jLabelSubTotal;
    private javax.swing.JLabel jLabelTotal;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTableConsulta;
    private javax.swing.JTextField jTextCedula;
    private javax.swing.JTextField jTextCodigo;
    private javax.swing.JTextField jTextCodigoVendedor;
    private javax.swing.JTextField jTextDireccion;
    private javax.swing.JTextField jTextEstablecimiento;
    private javax.swing.JTextField jTextNoPedido;
    private javax.swing.JTextField jTextNombre;
    private javax.swing.JTextArea jTextObservaciones;
    private javax.swing.JTextField jTextTelefono;
    private javax.swing.JPanel panelFondo;
    // End of variables declaration//GEN-END:variables

     /**
     * Verifico si el dato se encuentra en la base de datos,
     * si el dato es encontrado, entonces realiza la consulta.
     * @throws SQLException
     */
     public void verificaConsultaCliente() throws SQLException{        
         if(!cliente.isExistCodigo(jTextCodigo.getText())){
             if(!jTextCedula.getText().trim().equalsIgnoreCase(""))
                JOptionPane.showMessageDialog(null,"Cliente No Se Encuentra Registrado En El Sistema...!");
             else//"Cliente Vacio", si esta vacio entonces pregunta si kiere consulatr los clientes
                if(JOptionPane.showConfirmDialog(null,"Desea Consultar Clientes")==0){// RESPONDE SI
                     ClienteConsultar menuConsulta=new ClienteConsultar(rootPaneCheckingEnabled,this,jTextCodigo);
                     menuConsulta.setVisible(true);
             }
         }else{//si existe entonces envia la informacion a los campos
              Cliente clie=new Cliente();
              clie=cliente.consultaClienteCodigo(jTextCodigo.getText());
              jTextCedula.setText(clie.getCedula());
              jTextNombre.setText(clie.getNombre() + " " + clie.getApellido());
              //jTextApellido.setText(datos[3]);
              jTextDireccion.setText(clie.getDireccion());
              jTextEstablecimiento.setText(clie.getEstablecimiento());
              jTextTelefono.setText(clie.getTelefono());
              //activa los demas campos e inactiva la cedula
              jTextCodigo.setEditable(false);
              jTextCodigoVendedor.setEditable(true);
              jTextCodigoVendedor.requestFocus();
          }        
     }

     /**
     * Verifico si el dato se encuentra en la base de datos,
     * si el dato es encontrado, entonces realiza la consulta.
     * @throws SQLException
     */
     public void verificaConsultaVendedor() throws SQLException{
         if(jTextCodigoVendedor.getText().trim().equalsIgnoreCase("")){
            if(JOptionPane.showConfirmDialog(null,"Desea Consultar Vendedores")==0){// RESPONDE SI
               VendedorConsultar menuConsulta=new VendedorConsultar(rootPaneCheckingEnabled,this,jTextCodigoVendedor);
               menuConsulta.setVisible(true);
            }
         }else{           
             if(!vendedor.isExist(jTextCodigoVendedor.getText())){
                JOptionPane.showMessageDialog(null,"Este Vendedor No Se Encuentra Registrado");
             }else{//si existe entonces envia la informacion a los campos
                jTableConsulta.setEnabled(true);
                jTableConsulta.requestFocus();
                jTableConsulta.changeSelection(0, 0, false, false);
                jTextCodigoVendedor.setEditable(false);
             }
         }
     }


     /**
      * recibe String codigo cliente, en el campo codigo de la vista
      * @param codigo
      */
     public void setTextCodigoCliente(String codigo) throws SQLException{
       jTextCodigo.setText(codigo);
       jTextCodigo.requestFocus();
       verificaConsultaCliente();
     }

     /**
      * recibe AString codigo, en la celda de la tabla codigo
      * @param codigo
      */
     public void setTextCodigoTable(String texto,int fila) throws SQLException{
        jTableConsulta.setValueAt(texto, fila, 1);//fila, columna
        DetallesFactura();
     }
  

/**
 * para poder utilizar este metodo es neesario realizar lo siguiente:
 *  tablaModelo=(DefaultTableModel) jTableConsulta.getModel();
    tablaModelo.addTableModelListener(this);
 * asi tendra su escucha activa.
 *  * @param e
 */
    public void tableChanged(TableModelEvent e){       
        int row = e.getFirstRow();
        int col = e.getColumn();            
        Object codigo=null;

       if(col>1){
           codigo=jTableConsulta.getValueAt(row, 1);
           if(!codigo.equals(""))
              try {
                  DetallesFactura();
              } catch (SQLException ex) {
                Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
              }
       }
      
       if(col==1){
           codigo=jTableConsulta.getValueAt(row, 1);
           if(codigo.equals("")){
                menuConsultaProducto=new ProductoConsultar(rootPaneCheckingEnabled,this,null,null,row);
                menuConsultaProducto.setVisible(true);
           }else{
               try {
                   DetallesFactura();
                } catch (SQLException ex) {
                    Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
                }
           }
        }

        if(col==4)
             if(jTableConsulta.isColumnSelected(4)){
                codigo=jTableConsulta.getValueAt(row, 1);
                if(!codigo.equals("")){
                    try {
                        jTableConsulta.setCellSelectionEnabled(false);
                        String cod=(String) jTableConsulta.getValueAt(row, 1);
                        Double solicitud= Double.parseDouble((String) jTableConsulta.getValueAt(row, 4).toString());
                        double cantfactu=pedidoDetalles.cantFacturar(cod,solicitud);
                        jTableConsulta.setValueAt(cantfactu,row,5);

                    } catch (SQLException ex) {
                        Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
                    }
                 }
             }

        if(col==5)
             if(jTableConsulta.isColumnSelected(5)){
                codigo=jTableConsulta.getValueAt(row, 1);
                if(!codigo.equals("")){
                    try {
                        jTableConsulta.setCellSelectionEnabled(false);
                        String cod=(String) jTableConsulta.getValueAt(row, 1);
                        Double solicitud= Double.parseDouble((String) jTableConsulta.getValueAt(row, 5).toString());
                        double cantfactu=pedidoDetalles.cantFacturar(cod,solicitud);
                        
                        jTableConsulta.changeSelection(row+1, 1, false, false);
                        jTableConsulta.editCellAt(row, 1);
                       
                        tablaModelo.setValueAt(cantfactu,row,5);
                        
                         
                        jTableConsulta.setColumnSelectionInterval(row,1);
                        

                    } catch (SQLException ex) {
                        Logger.getLogger(FacturaRegistrar.class.getName()).log(Level.SEVERE, null, ex);
                    }
                 }
             }

//activo y desactivo los botones para evitar fallas al no tener productos
        if(jTableConsulta.getRowCount()>1){
            jButtonPedido.setEnabled(true);
            jButtonFacturar.setEnabled(true);
        } else{
            jButtonPedido.setEnabled(false);
            jButtonFacturar.setEnabled(false);
        }
    }

     /**
      * llenar el vector de detalles
      * ademas obtiene los valores de subtotal, iva y total.
      * @param fila del codigo del producto, y columna
      */
     public void DetallesFactura() throws SQLException{
        pedidoDetalles.matrizDetalles(jTableConsulta);
        totales();
    }

     /**
      * calcula los totales, subtotales e iva
      */
     public void totales() throws SQLException{
        Double[] datos=new Double[3];
        datos=facturaDetalles.getTotales(jTableConsulta);

        jLabelSubTotal.setText(NumberFormat.getCurrencyInstance().format(datos[0]));
        jLabelIva.setText(NumberFormat.getCurrencyInstance().format(datos[1]));
        jLabelTotal.setText(NumberFormat.getCurrencyInstance().format(datos[2]));
     }
     
     /**
      * Registra el Pedido y sus detalles
      * @throws SQLException
      */
    public void registraPedido() throws SQLException{
        if(!pedido.isExist(jTextNoPedido.getText())){//si no existe el pedido lo crea
            pedido.registraPedido(jTextNoPedido.getText(),fechaActual,jTextCodigo.getText(),jTextCodigoVendedor.getText(),true);
            pedidoDetalles.registrarDetallesTabla(jTableConsulta,jTextNoPedido.getText());
        }else{//si existe, lo actualiza
            pedidoDetalles.actualizarDetallesTabla(jTableConsulta,jTextNoPedido.getText());
        }
       
    }

    /**
      * Registra la factura y sus detalles
      * @throws SQLException
      */
    public void registraFactura() throws SQLException{
        registraPedido();
        Pedido ped=pedido.getPedido(jTextNoPedido.getText());
        ped.setEstado(false);
        pedido.actualizaPedido(ped);//actualizo el estado del pedido, lo coloco como facturado

        Double[] datos=new Double[3];
        datos=facturaDetalles.getTotales(jTableConsulta);
        java.sql.Date f=new java.sql.Date(WIDTH);
        
        factura.registraFactura(jLabelConsFactura.getText(),
                                fechaActual,
                                jTextObservaciones.getText(),
                                jTextNoPedido.getText(),
                                true,
                                datos[0],
                                datos[1],
                                datos[2]);

        facturaDetalles.registrarDetallesTabla(jTableConsulta,jLabelConsFactura.getText());
        jLabelConsFactura.setText((factura.getConsecutivo()+1)+"");
        clean();
        
         //imprimir reporte
            if(JOptionPane.showConfirmDialog(null,"Desea Imprimir la Factura")==0){// RESPONDE SI
                Reporte report=new Reporte();
                report.startReport("ReporteFacturaDeVenta.jasper",factura.getConsecutivo()+"");
            }else
                JOptionPane.showMessageDialog(null,"Operacion Exitosa...!");
    }

    /**
     * Limpiamos el formulario factura
     */
    private void clean(){
          pedidoDetalles.cleanTabla(jTableConsulta);//limpio la tabla

          jTextCodigo.setText("");
          jTextCodigo.setEditable(false);
          jTextCedula.setText("");
          jTextCedula.setEditable(false);
          jTextDireccion.setText("");
          jTextEstablecimiento.setText("");
          jTextNoPedido.setEditable(true);
          jTextNoPedido.setText("");
          jTextNoPedido.requestFocus();
          jTextNombre.setText("");
          jTextTelefono.setText("");
          jTextCodigoVendedor.setText("");
          jTextCodigoVendedor.setEditable(false);
          tablaModelo.addRow(new Object[]{""});
          jTableConsulta.setEnabled(false);
          jLabelTotal.setText("0.0");
          jLabelSubTotal.setText("0.0");
          jLabelIva.setText("0.0");
    }



    /**
     * Este metodo es utilizado para ajustar el tamaño de las celdas en la tabla.
     */
     public void ajustaTabla(){
      jTableConsulta.getColumnModel().getColumn(0).setPreferredWidth(40);//le doy el tamaño a la columna
      jTableConsulta.getColumnModel().getColumn(1).setPreferredWidth(70);//le doy el tamaño a la columna
      jTableConsulta.getColumnModel().getColumn(2).setPreferredWidth(200);
      jTableConsulta.getColumnModel().getColumn(3).setPreferredWidth(85);
      jTableConsulta.getColumnModel().getColumn(4).setPreferredWidth(85);
      jTableConsulta.getColumnModel().getColumn(8).setPreferredWidth(30);
  }

/**
 * eliminamos productos de los detalles, elimina la fila completa
 * @throws SQLException
 */
  public void eliminarProducto() throws SQLException{
      int row=jTableConsulta.getSelectedRow();

      jTableConsulta.setColumnSelectionAllowed(false);
      //selecciono la fila a borrar, simplemente sombreo la fila
      jTableConsulta.setRowSelectionAllowed(true);

      //condicion para borrar la fila confirman si estan seguros de borrar
      if(JOptionPane.showConfirmDialog(null,"Desea Eliminar este Producto?")==0){// RESPONDE SI         
          tablaModelo.removeRow(row);
      }
      //adiero una fila si me borran todas las filas evito kedarme sin filas
      if(tablaModelo.getRowCount()==0)
          tablaModelo.addRow(new Object[]{"",""});

      //actualizo los totales
      totales();
  }

    /**
     * carga el formulario con los datos del pedido consultado
     * @param Pedido
     * @throws SQLException
     */
      public void getPedido(Pedido ped) throws SQLException{
           jTextCodigo.setText(ped.getCodigoCliente());
           verificaConsultaCliente();
           jTextCodigoVendedor.setText(ped.getCodigoVendedor());
           jTextCodigoVendedor.requestFocus();
           pedidoDetalles.cargaDetallesTabla(jTableConsulta, ped.getConsecutivo());
           totales();
           jTextNoPedido.setEditable(false);
      }
}

